package com.stlm2.dems.shiro;

import com.stlm2.dems.user.dao.SystemPrivilegeDao;
import com.stlm2.dems.user.entity.IsValid;
import com.stlm2.dems.user.entity.PermissionType;
import com.stlm2.dems.user.entity.SystemPrivilege;
import com.stlm2.util.StringUtils;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import org.springframework.beans.factory.FactoryBean;

import javax.annotation.Resource;
import java.util.List;

//获取动态权限(针对URL的拦截)
public class ChainDefinitionSectionMetaSource implements
		FactoryBean<Section> {

	@Resource
	private SystemPrivilegeDao systemPrivilegeDao;

	@Override
	public Section getObject() throws Exception {
		Ini ini = new Ini();
		ini.load(SystemPrivilege.defaultPrivilege);
		Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
		if (CollectionUtils.isEmpty(section)) {
			section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
		}
		SystemPrivilege systemPrivilege=new SystemPrivilege();
		systemPrivilege.setIsValid(IsValid.Normal);
		systemPrivilege.setPermissionType(PermissionType.URL);
		List <SystemPrivilege>  systemPrivilegeList =systemPrivilegeDao.queryPageView(-1,-1,systemPrivilege).getRecords();

//		 循环数据库资源的url,对URL进行权限拦截
		for (SystemPrivilege systemPrivilege1 : systemPrivilegeList) {
			if (StringUtils.isNotNullAndEmpty(systemPrivilege1.getUrl()) && StringUtils.isNotNullAndEmpty(systemPrivilege1.getPermission())){
				section.put(systemPrivilege1.getUrl(), systemPrivilege1.getPermission());
			}
		}
		return section;
	}

	@Override
	public Class<?> getObjectType() {
		return Section.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
}
